<!-- TextToSpeechBatch.vue -->
<template>
  <div class="tts-batch">
    <!-- 页面标题和状态 -->
    <div class="tts-batch-header">
      <div class="status">{{ synthesizedCount }}/{{ totalCount }} 已合成</div>

      <!-- 添加导入按钮 -->
      <t-button theme="primary" @click="showImportDialog">
        <template #icon>
          <AddIcon />
        </template>
        导入文本
      </t-button>
    </div>

    <div class="tts-batch-content">
      <!-- 选项卡：当前任务和历史记录 -->
      <t-tabs v-model="state.activeTab" class="main-tabs">
        <!-- 当前任务选项卡 -->
        <t-tab-panel value="current" label="当前任务">
          <div class="current-task-content">
            <!-- TTS服务提供商选择 -->
            <div class="provider-selection">
              <t-radio-group v-model="state.ttsProvider">
                <t-radio value="openai">OpenAI TTS</t-radio>
                <t-radio value="google">Google TTS</t-radio>
              </t-radio-group>
            </div>

            <div class="auto-caption-settings">
              <t-checkbox v-model="state.autoGenerateCaption">
                合成时自动生成字幕
              </t-checkbox>
              <span class="setting-tip">开启后，合成音频时会自动为每个音频生成字幕</span>
            </div>

            <!-- OpenAI TTS 设置 -->
            <div v-if="state.ttsProvider === 'openai'" class="tts-settings-panel">
              <!-- 语音模型和语言选择区域 -->
              <div class="tts-settings">
                <div class="setting-item">
                  <div class="setting-label">模型:</div>
                  <t-select
                    v-model="state.selectedModel"
                    placeholder="选择模型"
                    class="setting-select"
                  >
                    <t-option
                      v-for="model in models"
                      :key="model.id"
                      :value="model.id"
                      :label="model.name"
                    >
                      {{ model.name }} - {{ model.description }}
                    </t-option>
                  </t-select>
                </div>

                <div class="setting-item">
                  <div class="setting-label">语音:</div>
                  <t-select
                    v-model="state.selectedVoice"
                    placeholder="选择语音"
                    class="setting-select"
                    :loading="state.voicesLoading"
                  >
                    <t-option
                      v-for="voice in voices"
                      :key="voice.id"
                      :value="voice.id"
                      :label="voice.name"
                    >
                      {{ voice.name }} - {{ voice.description }}
                    </t-option>
                  </t-select>
                </div>

                <div class="setting-item" v-if="useLanguageSelection">
                  <div class="setting-label">语言:</div>
                  <t-select
                    v-model="state.selectedLanguage"
                    placeholder="选择语言"
                    class="setting-select"
                  >
                    <t-option
                      v-for="language in languages"
                      :key="language.code"
                      :value="language.code"
                      :label="language.name"
                    >
                      {{ language.name }}
                    </t-option>
                  </t-select>
                </div>
              </div>

              <!-- 模型信息提示 -->
              <ModelInfoComponent :modelType="state.selectedModel" />

              <!-- 语音指令组件 - 仅对支持的模型显示 -->
              <VoiceInstructionComponent
                v-if="supportsVoiceInstructions"
                :modelType="state.selectedModel"
                @update:instructions="updateInstructions"
              />
            </div>

            <!-- Google TTS 设置 -->
            <div v-if="state.ttsProvider === 'google'" class="tts-settings-panel">
              <GoogleTtsComponent :voices="google_voices" @update:settings="updateGoogleSettings" />
            </div>

            <!-- 文本列表 -->
            <div class="text-list">
              <!-- 空状态 -->
              <div v-if="!textItems.length" class="empty-state">暂无文本，请先导入文本内容</div>

              <template v-else>
                <!-- 多选操作栏 -->
                <div class="batch-actions" v-if="textItems.length > 0">
                  <t-checkbox v-model="state.selectMode" @change="action.toggleSelectMode">
                    <span>多选模式</span>
                  </t-checkbox>

                  <template v-if="state.selectMode">
                    <div class="batch-info">已选择 {{ state.selectedItems.length }} 项</div>
                    <div class="batch-controls">
                      <t-button
                        size="small"
                        @click="action.selectCurrentPageItems"
                        v-if="getCurrentPageTextItems().length > 0 && !isCurrentPageFullySelected"
                      >
                        选择当前页
                      </t-button>
                      <t-button
                        size="small"
                        @click="action.deselectCurrentPageItems"
                        v-if="getCurrentPageTextItems().length > 0 && hasCurrentPageSelected"
                      >
                        取消选择当前页
                      </t-button>
                      <t-button
                        size="small"
                        @click="action.deselectAllItems"
                        v-if="state.selectedItems.length > 0"
                      >
                        清除选择
                      </t-button>
                      <t-button
                        size="small"
                        theme="primary"
                        @click="action.batchDownload"
                        v-if="state.selectedItems.length > 0"
                      >
                        <template #icon><DownloadIcon /></template>
                        批量下载 ({{ state.selectedItems.length }})
                      </t-button>
                      <t-button
                        size="small"
                        theme="danger"
                        @click="action.batchDeleteItems"
                        v-if="state.selectedItems.length > 0"
                      >
                        批量删除
                      </t-button>
                    </div>
                  </template>
                </div>

                <!-- 文本列表项 -->
                <div class="text-items">
                  <div
                    v-for="item in getCurrentPageTextItems()"
                    :key="item.id"
                    class="text-item"
                    :class="{
                      synthesized: item.audioUrl,
                      selected: state.selectedItems.includes(item.id)
                    }"
                    @click="state.selectMode ? action.toggleSelectItem(item.id) : null"
                  >
                    <!-- 选择框 -->
                    <div class="item-select" v-if="state.selectMode">
                      <t-checkbox
                        :checked="state.selectedItems.includes(item.id)"
                        @change="action.toggleSelectItem(item.id)"
                        @click.stop
                      />
                    </div>

                    <!-- 文本内容 -->
                    <div class="text-content">
                      <div class="text-title">
                        {{ item.name || '未命名' }}
                        <t-tag
                          v-if="item.translated"
                          size="small"
                          theme="success"
                          class="translated-tag"
                          >已翻译</t-tag
                        >
                      </div>
                      <div class="text-preview">
                        {{ item.text.substring(0, 50) + (item.text.length > 50 ? '...' : '') }}
                      </div>
                    </div>

                    <!-- 状态标签 -->
                    <div class="text-status">
                      <t-tag v-if="item.audioUrl" theme="success">已合成</t-tag>
                      <t-tag v-else-if="item.synthesizing" theme="warning">合成中</t-tag>
                      <t-tag v-else theme="default">待合成</t-tag>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="text-actions">
                      <t-button
                        v-if="item.audioUrl"
                        size="small"
                        @click.stop="action.previewAudio(item)"
                      >
                        <template #icon><PlayIcon /></template>
                        试听
                      </t-button>
                      <t-button
                        v-else
                        size="small"
                        theme="primary"
                        @click.stop="action.synthesizeSingle(item)"
                        :loading="item.synthesizing"
                        :disabled="!isReadyToSynthesize"
                      >
                        合成
                      </t-button>
                      <!-- 添加字幕生成按钮 -->
                      <t-button
                        v-if="!item.captionGenerating && !item.captionPath"
                        size="small"
                        theme="warning"
                        @click.stop="action.generateCaption(item)"
                        :disabled="!item.audioUrl"
                        title="生成字幕"
                      >
                        <template #icon><FileIcon /></template>
                        生成字幕
                      </t-button>

                      <!-- 字幕生成中状态 -->
                      <t-button
                        v-else-if="item.captionGenerating"
                        size="small"
                        theme="warning"
                        loading
                        disabled
                      >
                        生成中
                      </t-button>

                      <!-- 字幕已生成，显示下载按钮 -->
                      <t-dropdown
                        v-else-if="item.captionPath && item.captionStatus === 'completed'"
                        trigger="click"
                        :popup-props="{ overlayClassName: 'caption-dropdown' }"
                      >
                        <t-button size="small" theme="success">
                          <template #icon><SubtitleIcon /></template>
                          字幕操作
                        </t-button>
                        <t-dropdown-menu>
                          <t-dropdown-item @click="action.downloadCaption(item)">
                            <template #prefixIcon><DownloadIcon /></template>
                            下载字幕
                          </t-dropdown-item>
                          <t-dropdown-item @click="action.previewCurrCaption(item)" :disabled="item.captionStatus !== 'completed'">
                            <template #prefixIcon><FileIcon /></template>
                            编辑字幕
                          </t-dropdown-item>
                        </t-dropdown-menu>
                      </t-dropdown>

                      <!-- 字幕生成失败 -->
                      <t-button
                        v-else-if="item.captionStatus === 'failed'"
                        size="small"
                        theme="danger"
                        @click.stop="action.generateCaption(item)"
                        title="字幕生成失败，点击重试"
                      >
                        <template #icon><FileIcon /></template>
                        重新生成
                      </t-button>

                      <!-- 添加音频下载按钮 -->
                      <t-button
                        v-if="item.audioUrl"
                        size="small"
                        theme="default"
                        @click.stop="action.downloadAudio(item)"
                        title="下载音频"
                      >
                        <template #icon><DownloadIcon /></template>
                        下载音频
                      </t-button>
                      <t-button
                        theme="danger"
                        variant="text"
                        size="small"
                        @click.stop="action.deleteItem(item.id)"
                        title="删除"
                      >
                        <DeleteIcon />
                      </t-button>
                    </div>
                  </div>
                </div>

                <!-- 分页控件 -->
                <div
                  class="pagination-container"
                  v-if="textItems.length > state.textPagination.pageSize"
                >
                  <t-pagination
                    v-model="state.textPagination.current"
                    v-model:pageSize="state.textPagination.pageSize"
                    :total="textItems.length"
                    :page-size-options="[5, 10, 15, 50, 100]"
                    @change="action.onTextPageChange"
                    @page-size-change="action.onTextPageSizeChange"
                  />
                </div>
              </template>
            </div>

            <!-- 底部操作按钮 -->
            <div class="tts-actions">
              <t-button
                theme="primary"
                @click="action.synthesizeAll"
                :disabled="!isReadyToSynthesize || !hasPendingItems"
                :loading="state.batchSynthesizing"
              >
                批量合成
              </t-button>
              <t-button
                theme="warning"
                @click="action.synthesizeSelected"
                :disabled="!isReadyToSynthesize || !hasPendingItems"
                :loading="state.batchSynthesizing"
                v-if="state.selectedItems.length > 0"
              >
                合成选中
              </t-button>
              <t-button
                theme="success"
                @click="action.sendToVideoCreation"
                :disabled="!hasCompletedItems"
              >
                数字人视频制作
              </t-button>
              <t-button
                theme="success"
                @click="action.sendToVideoKpop"
                :disabled="!hasCompletedItems || !kicked"
              >
                视频混剪
              </t-button>
            </div>
          </div>
        </t-tab-panel>

        <!-- 历史记录选项卡 -->
        <t-tab-panel value="history" label="历史记录">
          <div class="history-content">
            <!-- 历史记录搜索栏 -->
            <div class="history-search">
              <t-input
                v-model="state.historySearchTerm"
                placeholder="搜索历史记录"
                clearable
                @enter="action.searchHistory"
              >
                <template #suffix-icon>
                  <SearchIcon />
                </template>
              </t-input>

              <t-button theme="primary" @click="action.searchHistory">搜索</t-button>
              <t-button theme="default" @click="action.refreshHistory">刷新</t-button>
            </div>

            <!-- 历史记录列表区域 -->
            <div class="history-list">
              <!-- 多选操作栏 -->
              <div class="history-batch-actions" v-if="historyItems.length > 0">
                <t-checkbox
                  v-model="state.historySelectMode"
                  @change="action.toggleHistorySelectMode"
                >
                  <span>多选模式</span>
                </t-checkbox>

                <template v-if="state.historySelectMode">
                  <div class="batch-info">已选择 {{ state.selectedHistoryItems.length }} 项</div>
                  <div class="batch-controls">
                    <t-button
                      size="small"
                      @click="action.selectAllHistoryItems"
                      v-if="
                        getCurrentPageHistoryItems().length > 0 &&
                        !isCurrentPageHistoryFullySelected
                      "
                    >
                      选择当前页
                    </t-button>
                    <t-button
                      size="small"
                      @click="action.deselectCurrentPageHistoryItems"
                      v-if="
                        getCurrentPageHistoryItems().length > 0 && hasCurrentPageHistorySelected
                      "
                    >
                      取消选择当前页
                    </t-button>
                    <t-button
                      size="small"
                      @click="action.deselectAllHistoryItems"
                      v-if="state.selectedHistoryItems.length > 0"
                    >
                      取消选择
                    </t-button>
                    <t-button
                      size="small"
                      theme="primary"
                      @click="action.batchDownloadHistory"
                      v-if="state.selectedHistoryItems.length > 0"
                    >
                      <template #icon><DownloadIcon /></template>
                      批量下载 ({{ state.selectedHistoryItems.length }})
                    </t-button>
                    <t-button
                      size="small"
                      theme="danger"
                      @click="action.batchDeleteHistoryItems"
                      v-if="state.selectedHistoryItems.length > 0"
                    >
                      批量删除
                    </t-button>
                  </div>
                </template>
              </div>

              <!-- 加载中状态 -->
              <div v-if="state.historyLoading" class="history-loading">
                <t-loading />
              </div>

              <!-- 空状态 -->
              <div v-else-if="!historyItems.length" class="empty-state">暂无历史记录</div>

              <!-- 历史记录列表 -->
              <div v-else class="history-items">
                <div
                  v-for="item in getCurrentPageHistoryItems()"
                  :key="item.id"
                  class="history-item"
                  :class="{ selected: state.selectedHistoryItems.includes(item.id) }"
                  @click="state.historySelectMode ? action.toggleSelectHistoryItem(item.id) : null"
                >
                  <!-- 选择框 -->
                  <div class="item-select" v-if="state.historySelectMode">
                    <t-checkbox
                      :checked="state.selectedHistoryItems.includes(item.id)"
                      @change="action.toggleSelectHistoryItem(item.id)"
                      @click.stop
                    />
                  </div>

                  <!-- 历史记录内容 -->
                  <div class="history-content">
                    <div class="history-title">{{ item.name || '未命名' }}</div>
                    <div class="history-info">
                      <t-tag theme="primary" size="small">{{ getModelName(item.model) }}</t-tag>
                      <t-tag theme="success" size="small">{{ getVoiceName(item.voice) }}</t-tag>
                      <span class="history-time">{{ formatDate(item.created_at) }}</span>
                    </div>
                    <div class="history-text">
                      {{ item.text.substring(0, 80) + (item.text.length > 80 ? '...' : '') }}
                    </div>
                    <div v-if="item.instructions" class="history-instructions">
                      <t-tag theme="warning" size="small">带语音指令</t-tag>
                    </div>
                    <!-- 添加字幕状态标签 -->
                    <div v-if="item.caption_status && item.caption_status !== 'none'" class="history-caption-status">
                      <t-tag
                        v-if="item.caption_status === 'completed'"
                        theme="success"
                        size="small"
                      >
                        <template #icon><CheckCircleIcon /></template>
                        有字幕
                      </t-tag>
                      <t-tag
                        v-else-if="item.caption_status === 'failed'"
                        theme="danger"
                        size="small"
                      >
                        字幕生成失败
                      </t-tag>
                    </div>
                  </div>

                  <!-- 操作按钮 -->
                  <div class="history-actions">
                    <t-button size="small" @click="action.previewHistoryAudio(item)">
                      试听
                    </t-button>
                    <t-button size="small" theme="primary" @click="action.useHistoryAudio(item)">
                      使用
                    </t-button>
                    <t-button @click="action.previewCaption(item)" :disabled="item.caption_status !== 'completed'">
                      <template #prefixIcon><FileIcon /></template>
                      编辑字幕
                    </t-button>
                    <t-button @click="action.downloadHistoryAudio(item)">
                      <template #prefixIcon><DownloadIcon /></template>
                      下载音频
                    </t-button>
                    <t-button @click="action.downloadHistoryCaption(item)" :disabled="item.caption_status !== 'completed'">
                      <template #prefixIcon><DownloadIcon /></template>
                      下载字幕
                    </t-button>
                    <t-button
                      theme="danger"
                      variant="text"
                      size="small"
                      @click="action.deleteHistoryItem(item.id)"
                      title="删除"
                    >
                      <DeleteIcon />
                    </t-button>
                  </div>
                </div>
              </div>

              <!-- 分页控件 -->
              <div class="pagination-container">
                <t-pagination
                  v-model="state.historyPagination.current"
                  v-model:pageSize="state.historyPagination.pageSize"
                  :total="historyItems.length"
                  :page-size-options="[5, 10, 15, 50, 100]"
                  @change="action.onHistoryPageChange"
                  @page-size-change="action.onHistoryPageSizeChange"
                />
              </div>
            </div>

            <!-- 历史记录底部操作按钮 -->
            <div class="history-actions">
              <t-button
                theme="success"
                @click="action.sendSelectedHistoryToVideoCreation"
                :disabled="!state.historySelectMode || state.selectedHistoryItems.length === 0"
              >
                {{
                  state.historySelectMode
                    ? `数字人视频制作 ${state.selectedHistoryItems.length} 项`
                    : '数字人视频制作'
                }}
              </t-button>

              <t-button
                theme="primary"
                @click="action.useHistoryAudios"
                :disabled="!state.historySelectMode || state.selectedHistoryItems.length === 0"
              >
                {{
                  state.historySelectMode
                    ? `添加到当前任务 ${state.selectedHistoryItems.length} 项`
                    : '添加到当前任务'
                }}
              </t-button>

              <t-button
                theme="warning"
                @click="action.sendHistoryToVideoCreation"
                :disabled="!historyItems.length || state.historySelectMode"
              >
                导入全部
              </t-button>

              <t-button
                theme="danger"
                variant="outline"
                @click="action.clearAllHistory"
                :disabled="!historyItems.length"
              >
                清空历史记录
              </t-button>
            </div>
          </div>
        </t-tab-panel>
      </t-tabs>
    </div>

    <!-- 导入翻译弹窗 -->
    <TtsImportTranslation
      v-model:visible="importDialogVisible"
      :modelType="state.selectedModel"
      @import-items="handleImportedTexts"
    />

    <CaptionPreviewDialog
      v-model:visible="captionPreviewVisible"
      :history-id="captionPreviewId"
      :title="captionPreviewTitle"
    />

    <!-- 批量下载对话框 -->
    <BatchDownloadDialog
      v-model:visible="batchDownloadVisible"
      @confirm="action.handleBatchDownloadConfirm"
    />

    <!-- 确认删除对话框 -->
    <t-dialog
      v-model:visible="state.deleteConfirmVisible"
      header="确认删除"
      width="400px"
      :confirm-btn="{ content: '删除', theme: 'danger' }"
      :cancel-btn="{ content: '取消' }"
      @confirm="action.confirmDelete"
    >
      <p>{{ state.deleteConfirmMessage }}</p>
    </t-dialog>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
import { v4 as uuidv4 } from 'uuid'
import {
  AddIcon, DeleteIcon, DownloadIcon,
  FileIcon, SubtitleIcon, SearchIcon,
  CheckCircleIcon, MoreIcon, PlayIcon
} from 'tdesign-icons-vue-next'
import {
  getAvailableTtsModels,
  getAvailableVoices,
  getGoogleAllVoices,
  getSupportedLanguages,
  speechToTextWithGoogle,
  synthesizeGoogleSpeech,
  synthesizeSpeech
} from '@renderer/api/ttsApi'

import {
  addTtsHistory,
  batchDownloadFiles,
  deleteAllTtsHistory,
  deleteTtsHistory,
  downloadAudioFile,
  downloadCaptionFile,
  getAllTtsHistory,
  searchTtsHistory,
  sendVideoToKpop,
  updateTtsHistoryCaption,
  updateTtsHistoryId
} from '@renderer/api/ttsHistory'
import VoiceInstructionComponent from './VoiceInstructionComponent.vue'
import ModelInfoComponent from '@renderer/views/audio/components/ModelInfoComponent.vue'
import GoogleTtsComponent from '@renderer/views/audio/components/GoogleTtsComponent.vue'
import TtsImportTranslation from '@renderer/views/audio/components/TtsImportTranslation.vue'
import CaptionPreviewDialog from '@renderer/views/audio/components/CaptionPreviewDialog.vue'
import BatchDownloadDialog from '@renderer/views/audio/components/BatchDownloadDialog.vue'
import { getBaseUrl } from '@renderer/api/assetPaths'

// 添加新地响应式变量
const captionPreviewVisible = ref(false)
const captionPreviewId = ref(null)
const captionPreviewTitle = ref('')

// 添加批量下载对话框的响应式变量
const batchDownloadVisible = ref(false)
const batchDownloadType = ref('current') // 'current' 或 'history'

// 添加一个响应式变量来存储语言列表
const languages = ref([])
const route = useRoute()
const router = useRouter()

// 可用语音列表
const voices = ref([])

// 谷歌语音列表
const google_voices = ref({})

const kicked = ref(true)

// Google TTS 设置
const googleTtsSettings = ref({
  languageCode: '',
  ssmlGender: '',
  name: '',
  speakingRate: 1.0
})

const assetPaths = ref('')

// 更新 Google TTS 设置
const updateGoogleSettings = (settings) => {
  googleTtsSettings.value = settings
}

// 导入对话框状态
const importDialogVisible = ref(false)

// 显示导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true
}

// 处理导入文本
const handleImportedTexts = (items) => {
  textItems.value = [...items, ...textItems.value]
  // 导入后切换到第一页，确保用户能看到新导入的内容
  state.textPagination.current = 1
}

// 加载特定模型支持的音色
const loadVoicesForModel = async (modelId) => {
  if (!modelId) return

  try {
    state.voicesLoading = true
    const availableVoices = await getAvailableVoices(modelId)
    voices.value = availableVoices

    // 如果当前选择的音色不在新的列表中，选择第一个可用的音色
    if (availableVoices.length > 0 && !availableVoices.some((v) => v.id === state.selectedVoice)) {
      state.selectedVoice = availableVoices[0].id
    }
  } catch (error) {
    console.error('加载模型支持的音色失败:', error)
    MessagePlugin.error('加载音色列表失败: ' + (error.message || '未知错误'))
  } finally {
    state.voicesLoading = false
  }
}

// 可用模型列表
const models = ref([
  // 预设模型列表，在API加载失败时显示
  { id: 'tts-1', name: 'TTS-1', description: '标准TTS模型' },
  { id: 'tts-1-hd', name: 'TTS-1-HD', description: '高清TTS模型' },
  { id: 'gpt-4o-audio-preview', name: 'GPT-4o Audio', description: '支持多语言' },
  { id: 'gpt-4o-mini-audio-preview', name: 'GPT-4o Mini Audio', description: '轻量版多语言模型' },
  { id: 'gpt-4o-mini-tts', name: 'GPT-4o Mini TTS', description: '支持自定义语音指令' }
])

const props = defineProps({
  listener: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['sendToVideoCreation'])

const state = reactive({
  activeTab: 'current', // 当前选项卡：current/history
  ttsProvider: 'openai', // 默认使用OpenAI提供商
  selectedModel: 'gpt-4o-mini-audio-preview', // 默认使用gpt-4o-mini-audio-preview模型
  selectedVoice: 'alloy',
  selectedLanguage: 'Chinese',
  batchSynthesizing: false,
  voiceInstructions: null, // 语音指令

  // 添加自动生成字幕的配置
  autoGenerateCaption: true, // 默认开启自动生成字幕

  // 历史记录多选模式
  historySelectMode: false,
  // 已选择的历史记录项ID列表
  selectedHistoryItems: [],

  // 添加文本列表分页状态
  textPagination: {
    current: 1,
    pageSize: 5
  },

  // 添加历史记录分页状态
  historyPagination: {
    current: 1,
    pageSize: 5
  },

  // 删除相关
  deleteConfirmVisible: false,
  deleteConfirmMessage: '',
  itemToDelete: null,
  isHistoryItem: false, // 标记是否是历史记录项

  // 选择模式
  selectMode: false,
  selectedItems: [],

  // 历史记录相关
  historySearchTerm: '',
  historyLoading: false,

  // 新增属性
  voicesLoading: false,

  // 批量删除模式标记
  batchDeleteMode: false
})

// 添加获取当前页文本项的方法
const getCurrentPageTextItems = () => {
  const startIndex = (state.textPagination.current - 1) * state.textPagination.pageSize
  const endIndex = startIndex + state.textPagination.pageSize
  return textItems.value.slice(startIndex, endIndex)
}

// 添加获取当前页历史记录项的方法
const getCurrentPageHistoryItems = () => {
  const startIndex = (state.historyPagination.current - 1) * state.historyPagination.pageSize
  const endIndex = startIndex + state.historyPagination.pageSize
  return historyItems.value.slice(startIndex, endIndex)
}

// 文本列表
const textItems = ref([])

// 历史记录列表
const historyItems = ref([])

// 计算属性：是否需要显示语言选择器（GPT-4o系列需要）
const useLanguageSelection = computed(() => {
  return (
    state.selectedModel === 'gpt-4o-audio-preview' ||
    state.selectedModel === 'gpt-4o-mini-audio-preview'
  )
})

// 计算属性：是否支持语音指令（仅gpt-4o-mini-tts支持）
const supportsVoiceInstructions = computed(() => {
  return state.selectedModel === 'gpt-4o-mini-tts'
})

// 计算属性：已合成的文本数量
const synthesizedCount = computed(() => {
  return textItems.value.filter((item) => item.audioUrl).length
})

// 计算属性：文本总数
const totalCount = computed(() => {
  return textItems.value.length
})

// 计算属性：是否有待合成的项目
const hasPendingItems = computed(() => {
  return textItems.value.some((item) => !item.audioUrl && !item.synthesizing)
})

// 计算属性：是否有已完成合成的项目
const hasCompletedItems = computed(() => {
  return textItems.value.some((item) => item.audioUrl)
})

// 计算属性：是否已经准备好进行合成（已选择语音和模型）
const isReadyToSynthesize = computed(() => {
  if (state.ttsProvider === 'openai') {
    // OpenAI TTS 需要选择模型和语音
    return state.selectedVoice && state.selectedModel
  } else if (state.ttsProvider === 'google') {
    // Google TTS 需要选择语言、性别和音色
    return (
      googleTtsSettings.value.languageCode &&
      googleTtsSettings.value.ssmlGender &&
      googleTtsSettings.value.name
    )
  }
  return false
})

// 计算当前页是否全部选中
const isCurrentPageFullySelected = computed(() => {
  const currentPageItems = getCurrentPageTextItems()
  return (
    currentPageItems.length > 0 &&
    currentPageItems.every((item) => state.selectedItems.includes(item.id))
  )
})

// 计算当前页是否有选中项
const hasCurrentPageSelected = computed(() => {
  const currentPageItems = getCurrentPageTextItems()
  return currentPageItems.some((item) => state.selectedItems.includes(item.id))
})

// 计算当前页历史记录是否全部选中
const isCurrentPageHistoryFullySelected = computed(() => {
  const currentPageItems = getCurrentPageHistoryItems()
  return (
    currentPageItems.length > 0 &&
    currentPageItems.every((item) => state.selectedHistoryItems.includes(item.id))
  )
})

// 计算当前页历史记录是否有选中项
const hasCurrentPageHistorySelected = computed(() => {
  const currentPageItems = getCurrentPageHistoryItems()
  return currentPageItems.some((item) => state.selectedHistoryItems.includes(item.id))
})

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '未知'
  const date = new Date(timestamp)
  return date.toLocaleString()
}

// 获取模型名称
const getModelName = (modelId) => {
  const model = models.value.find((m) => m.id === modelId)
  return model ? model.name : modelId
}

// 获取语音名称
const getVoiceName = (voiceId) => {
  const voice = voices.value.find((v) => v.id === voiceId)
  return voice ? voice.name : voiceId
}

// 更新语音指令
const updateInstructions = (instructions) => {
  state.voiceInstructions = instructions
}

// 监听选项卡变化，加载历史记录
watch(
  () => state.activeTab,
  (newTab) => {
    if (newTab === 'history') {
      action.loadHistory()
    }
  }
)

// 监听模型变化，加载对应的音色
watch(
  () => state.selectedModel,
  async (newModel) => {
    // 如果模型不支持语音指令，重置指令
    if (newModel !== 'gpt-4o-mini-tts') {
      state.voiceInstructions = null
    }

    // 加载新模型支持的音色
    await loadVoicesForModel(newModel)
  }
)

// 监听配置变化并保存
watch(
  () => ({
    autoGenerateCaption: state.autoGenerateCaption,
    selectedModel: state.selectedModel,
    selectedVoice: state.selectedVoice,
    ttsProvider: state.ttsProvider
  }),
  (newConfig) => {
    // 保存配置到本地存储
    localStorage.setItem('tts-batch-config', JSON.stringify(newConfig))
  },
  { deep: true }
)

// 加载可用的语音和模型列表
const loadData = async () => {
  try {
    // 并行加载模型和语言列表
    const [modelsResult, languagesResult] = await Promise.all([
      getAvailableTtsModels(),
      getSupportedLanguages()
    ])

    // 设置模型列表
    models.value = modelsResult

    // 设置语言列表
    languages.value = languagesResult

    // 设置默认模型
    if (!state.selectedModel && modelsResult.length > 0) {
      state.selectedModel = modelsResult[0].id
    }

    // 设置默认语言（如果语言列表不为空且尚未设置语言）
    if (languagesResult.length > 0 && !state.selectedLanguage) {
      // 默认选择中文，如果有的话
      const chineseLanguage = languagesResult.find((lang) => lang.code === 'Chinese')
      state.selectedLanguage = chineseLanguage ? chineseLanguage.code : languagesResult[0].code
    }

    // 加载当前选定模型支持的音色列表
    await loadVoicesForModel(state.selectedModel)
  } catch (error) {
    console.error('加载模型和音色列表失败:', error)
    MessagePlugin.error('加载数据失败: ' + (error.message || '未知错误'))
  }
}

// 加载谷歌可用音色
const loadGoogleVoices = async () => {
  try {
    // 从API加载谷歌音色列表
    google_voices.value = await getGoogleAllVoices()
  } catch (e) {
    console.error('加载谷歌音色列表失败:', e)
    MessagePlugin.error('加载谷歌音色列表失败: ' + (e.message || '未知错误'))
  }
}

const action = {
  // 生成字幕
  async generateCaption(item) {
    if (!item.audioUrl) {
      await MessagePlugin.warning('请先合成音频')
      return
    }

    try {
      // 使用 item 自身的状态，而不是全局状态
      item.captionGenerating = true
      item.captionStatus = 'generating'

      // 触发视图更新
      textItems.value = [...textItems.value]

      // 调用语音转文字API生成字幕
      const captionPath = await speechToTextWithGoogle(
        item.audioUrl,
        item.language || 'zh',
        'srt',
        null, // 使用默认输出目录
        item.text // 提供原始文本以提高准确性
      )

      // 更新项目状态
      item.captionPath = captionPath
      item.captionStatus = 'completed'
      item.captionGenerating = false

      // 如果项目已经在数据库中（有historyId），更新数据库
      if (item.historyId) {
        await updateTtsHistoryCaption(item.historyId, captionPath, 'completed')
      }

      await MessagePlugin.success('字幕生成成功')
    } catch (error) {
      console.error('字幕生成失败:', error)
      item.captionStatus = 'failed'
      item.captionGenerating = false

      // 触发视图更新
      textItems.value = [...textItems.value]

      if (item.historyId) {
        await updateTtsHistoryCaption(item.historyId, null, 'failed', error.message)
      }

      await MessagePlugin.error('字幕生成失败: ' + (error.message || '未知错误'))
    }
  },

  // 创建自动生成字幕的方法
  async generateCaptionAuto(item) {
    if (!item.audioUrl) {
      console.log('音频文件不存在，跳过字幕生成')
      return
    }

    try {
      item.captionGenerating = true
      item.captionStatus = 'generating'

      const captionPath = await speechToTextWithGoogle(
        item.audioUrl,
        item.language || 'zh',
        'srt',
        null,
        item.text
      )

      item.captionPath = captionPath
      item.captionStatus = 'completed'
      item.captionGenerating = false

      if (item.historyId) {
        await updateTtsHistoryCaption(item.historyId, captionPath, 'completed')
      }

    } catch (error) {
      console.error(`字幕自动生成失败 (${item.name}):`, error)
      item.captionStatus = 'failed'
      item.captionGenerating = false

      if (item.historyId) {
        await updateTtsHistoryCaption(item.historyId, null, 'failed', error.message)
      }
    }
  },

  // 下载音频
  async downloadAudio(item) {
    if (!item.audioUrl) {
      await MessagePlugin.warning('音频文件不存在')
      return
    }

    try {
      // 如果有历史记录ID，使用历史记录下载
      if (item.historyId) {
        const result = await downloadAudioFile(item.historyId)
        if (result.success) {
          await MessagePlugin.success('音频文件已保存')
        }
      } else {
        // 否则直接使用文件路径下载
        // 这里需要实现临时文件的下载逻辑
        await MessagePlugin.warning('请先保存到历史记录')
      }
    } catch (error) {
      await MessagePlugin.error('下载失败: ' + (error.message || '未知错误'))
    }
  },

  // 下载字幕
  async downloadCaption(item) {
    if (!item.captionPath) {
      await MessagePlugin.warning('字幕文件不存在')
      return
    }

    try {
      if (item.historyId) {
        const result = await downloadCaptionFile(item.historyId)
        if (result.success) {
          await MessagePlugin.success('字幕文件已保存')
        }
      } else {
        await MessagePlugin.warning('请先保存到历史记录')
      }
    } catch (error) {
      await MessagePlugin.error('下载失败: ' + (error.message || '未知错误'))
    }
  },

  // 预览字幕
  previewCaption(item) {
    if (!item.id || item.caption_status !== 'completed') {
      MessagePlugin.warning('字幕不可用')
      return
    }

    captionPreviewId.value = item.id
    captionPreviewTitle.value = item.name || '未命名'
    captionPreviewVisible.value = true
  },

  // 预览字幕
  previewCurrCaption(item) {
    if (!item.historyId || item.captionStatus !== 'completed') {
      MessagePlugin.warning('字幕不可用')
      return
    }

    captionPreviewId.value = item.historyId
    captionPreviewTitle.value = item.name || '未命名'
    captionPreviewVisible.value = true
  },

  // 下载历史记录音频
  async downloadHistoryAudio(item) {
    try {
      const result = await downloadAudioFile(item.id)
      if (result.success) {
        await MessagePlugin.success('音频文件已保存')
      }
    } catch (error) {
      await MessagePlugin.error('下载失败: ' + (error.message || '未知错误'))
    }
  },

  // 下载历史记录字幕
  async downloadHistoryCaption(item) {
    if (item.caption_status !== 'completed') {
      await MessagePlugin.warning('字幕文件不存在')
      return
    }

    try {
      const result = await downloadCaptionFile(item.id)
      if (result.success) {
        await MessagePlugin.success('字幕文件已保存')
      }
    } catch (error) {
      await MessagePlugin.error('下载失败: ' + (error.message || '未知错误'))
    }
  },

  // 批量下载 - 当前任务
  batchDownload() {
    if (state.selectedItems.length === 0) {
      MessagePlugin.warning('请选择要下载的项目')
      return
    }

    batchDownloadType.value = 'current'
    batchDownloadVisible.value = true
  },

  // 批量下载 - 历史记录
  batchDownloadHistory() {
    if (state.selectedHistoryItems.length === 0) {
      MessagePlugin.warning('请选择要下载的项目')
      return
    }

    batchDownloadType.value = 'history'
    batchDownloadVisible.value = true
  },

  // 处理批量下载确认
  async handleBatchDownloadConfirm(option) {
    try {
      let result
      const isHistory = batchDownloadType.value === 'history'
      const selectedIds = isHistory
        ? [...state.selectedHistoryItems]
        : [...state.selectedItems];

      // 根据选项确定下载内容
      const includeAudio = option === 'both' || option === 'audio'
      const includeCaption = option === 'both' || option === 'caption'

      // 对于当前任务，需要先获取有历史记录ID的项目
      if (!isHistory) {
        const itemsWithHistory = textItems.value
          .filter(item => state.selectedItems.includes(item.id) && item.id)
          .map(item => item.id)

        if (itemsWithHistory.length === 0) {
          await MessagePlugin.warning('选中的项目还未保存到历史记录')
          return
        }

        result = await batchDownloadFiles(itemsWithHistory, includeAudio, includeCaption)
      } else {
        result = await batchDownloadFiles(selectedIds, includeAudio, includeCaption)

      }

      if (result.success) {
        await MessagePlugin.success('批量下载成功')
      }
    } catch (error) {
      await MessagePlugin.error('批量下载失败: ' + (error.message || '未知错误'))
    }
  },

  // 切换选择模式
  toggleSelectMode(checked) {
    state.selectMode = checked
    // 切换模式时清空选择
    if (!checked) {
      state.selectedItems = []
    }
  },

  // 选择当前页所有项目
  selectCurrentPageItems() {
    const currentPageItems = getCurrentPageTextItems()
    const currentPageIds = currentPageItems.map((item) => item.id)

    // 合并当前已选择的和当前页的ID，避免重复
    state.selectedItems = [...new Set([...state.selectedItems, ...currentPageIds])]

    MessagePlugin.success(`已选择当前页 ${currentPageItems.length} 项`)
  },

  // 取消选择当前页所有项目
  deselectCurrentPageItems() {
    const currentPageIds = getCurrentPageTextItems().map((item) => item.id)
    state.selectedItems = state.selectedItems.filter((id) => !currentPageIds.includes(id))

    MessagePlugin.success('已取消选择当前页')
  },

  // 取消选择所有项目
  deselectAllItems() {
    state.selectedItems = []
    MessagePlugin.success('已清除所有选择')
  },

  // 批量删除选中项目
  batchDeleteItems() {
    if (state.selectedItems.length === 0) {
      MessagePlugin.warning('请先选择需要删除的项目')
      return
    }

    state.deleteConfirmMessage = `确定要删除选中的 ${state.selectedItems.length} 项吗？此操作不可恢复。`
    state.deleteConfirmVisible = true
  },

  // 取消选择当前页历史记录
  deselectCurrentPageHistoryItems() {
    const currentPageIds = getCurrentPageHistoryItems().map((item) => item.id)
    state.selectedHistoryItems = state.selectedHistoryItems.filter(
      (id) => !currentPageIds.includes(id)
    )

    MessagePlugin.success('已取消选择当前页')
  },

  // 批量删除历史记录
  batchDeleteHistoryItems() {
    if (state.selectedHistoryItems.length === 0) {
      MessagePlugin.warning('请至少选择一条历史记录')
      return
    }

    // 设置确认对话框信息
    state.deleteConfirmMessage = `确定要删除选中的 ${state.selectedHistoryItems.length} 条历史记录吗？此操作不可恢复。`
    state.isHistoryItem = true
    // 使用特殊标记表示这是批量删除
    state.batchDeleteMode = true
    state.deleteConfirmVisible = true
  },

  // 切换历史记录多选模式
  toggleHistorySelectMode(checked) {
    state.historySelectMode = checked
    // 切换模式时清空选择
    if (!checked) {
      state.selectedHistoryItems = []
    }
  },

  // 切换选择单个历史记录
  toggleSelectHistoryItem(id) {
    if (state.selectedHistoryItems.includes(id)) {
      state.selectedHistoryItems = state.selectedHistoryItems.filter((itemId) => itemId !== id)
    } else {
      state.selectedHistoryItems.push(id)
    }
  },

  // 选择当前页所有历史记录
  selectAllHistoryItems() {
    const currentPageItems = getCurrentPageHistoryItems()
    const currentPageIds = currentPageItems.map((item) => item.id)

    // 合并当前已选择的和当前页的ID，避免重复
    state.selectedHistoryItems = [...new Set([...state.selectedHistoryItems, ...currentPageIds])]

    MessagePlugin.success(`已选择当前页 ${currentPageItems.length} 项`)
  },

  // 取消选择所有历史记录
  deselectAllHistoryItems() {
    state.selectedHistoryItems = []
    MessagePlugin.success('已取消所有选择')
  },

  // 将选中的历史记录发送到视频制作
  sendSelectedHistoryToVideoCreation() {
    if (state.selectedHistoryItems.length === 0) {
      MessagePlugin.warning('请至少选择一条历史记录')
      return
    }

    // 获取选中的历史记录项
    const selectedItems = historyItems.value.filter((item) =>
      state.selectedHistoryItems.includes(item.id)
    )

    // 转换为批处理所需的格式
    const audioItems = selectedItems.map((item) => ({
      id: uuidv4(),
      type: 'audio',
      name: item.name,
      audioUrl: item.audio_path,
      duration: item.duration
        ? `${Math.floor(item.duration / 60)}:${(item.duration % 60).toString().padStart(2, '0')}`
        : '未知时长',
      createdAt: new Date(item.created_at).toISOString()
    }))

    // 发送到父组件进行处理
    emit('sendToVideoCreation', audioItems)

    MessagePlugin.success(`已将 ${audioItems.length} 个选中的历史语音发送到视频制作`)

    // 清空选择并关闭选择模式
    state.selectedHistoryItems = []
    state.historySelectMode = false
  },

  // 文本列表分页方法
  onTextPageChange(pageInfo) {
    state.textPagination.current = pageInfo.current
  },

  onTextPageSizeChange(pageSize) {
    state.textPagination.pageSize = pageSize
    state.textPagination.current = 1 // 重置到第一页
  },

  // 历史记录分页方法
  onHistoryPageChange(pageInfo) {
    state.historyPagination.current = pageInfo.current
  },

  onHistoryPageSizeChange(pageSize) {
    state.historyPagination.pageSize = pageSize
    state.historyPagination.current = 1 // 重置到第一页
  },

  // 合成单条文本
  async synthesizeSingle(item) {
    if (!isReadyToSynthesize.value) {
      await MessagePlugin.warning(
        state.ttsProvider === 'openai' ? '请先选择模型和语音' : '请先选择语言、性别和音色'
      )
      return
    }

    try {
      // 设置状态为合成中
      item.synthesizing = true

      // 调用语音合成 API
      let result

      if (state.ttsProvider === 'openai') {
        // 使用OpenAI TTS
        result = await synthesizeSpeech(
          item.text,
          state.selectedModel,
          state.selectedVoice,
          useLanguageSelection.value ? state.selectedLanguage : null,
          supportsVoiceInstructions.value ? state.voiceInstructions : null
        )
      } else {
        // 使用Google TTS
        result = await synthesizeGoogleSpeech(
          item.text,
          googleTtsSettings.value.languageCode,
          googleTtsSettings.value.ssmlGender,
          googleTtsSettings.value.name,
          googleTtsSettings.value.speakingRate
        )
      }

      // 更新项目
      item.audioUrl = result.path
      item.duration = result.duration
      item.language = state.ttsProvider === 'openai'
        ? useLanguageSelection.value ? state.selectedLanguage : null
        : googleTtsSettings.value.languageCode
      item.synthesizing = false

      // 保存到历史记录
      const historyItem = await addTtsHistory({
        name: item.name,
        text: item.text,
        originalName: item.originalName,
        originalText: item.originalText,
        audioPath: result.path,
        duration: result.duration,
        model: state.ttsProvider === 'openai' ? state.selectedModel : 'google-tts',
        voice: state.ttsProvider === 'openai' ? state.selectedVoice : googleTtsSettings.value.name,
        language: state.ttsProvider === 'openai'
          ? useLanguageSelection.value ? state.selectedLanguage : null
          : googleTtsSettings.value.languageCode,
        instructions: state.ttsProvider === 'openai'
          ? supportsVoiceInstructions.value ? state.voiceInstructions : null
          : JSON.stringify({
            ssmlGender: googleTtsSettings.value.ssmlGender,
            speakingRate: googleTtsSettings.value.speakingRate
          }),
        captionPath: item.captionPath || null,
        captionStatus: item.captionStatus || 'none',
        captionFormat: 'srt'
      })

      item.historyId = historyItem.id

      await updateTtsHistoryId(historyItem.id, item.historyId)

      await MessagePlugin.success('语音合成成功')

      // 更新文本列表，触发视图更新
      textItems.value = [...textItems.value]

      // 如果需要自动生成字幕
      if (state.autoGenerateCaption) {
        try {
          await action.generateCaptionAuto(item)
          // 再次更新视图
          textItems.value = [...textItems.value]
          await MessagePlugin.success('字幕合成成功')
        } catch (error) {
          console.error(`字幕生成失败 (${item.name}):`, error)
        }
      }

      // 如果在历史记录标签页，刷新历史记录
      if (state.activeTab === 'history') {
        await action.loadHistory()
      }
    } catch (error) {
      console.error('语音合成失败:', error)
      await MessagePlugin.error('语音合成失败: ' + (error.message || '未知错误'))
      item.synthesizing = false
    }
  },

  // 批量合成所有文本
  async synthesizeAll() {
    if (!isReadyToSynthesize.value) {
      MessagePlugin.warning(
        state.ttsProvider === 'openai' ? '请先选择模型和语音' : '请先选择语言、性别和音色'
      )
      return
    }

    if (!hasPendingItems.value) {
      MessagePlugin.warning('没有待合成的文本')
      return
    }

    try {
      state.batchSynthesizing = true

      // 获取所有待合成的项目
      const pendingItems = textItems.value.filter((item) => !item.audioUrl && !item.synthesizing)

      await MessagePlugin.info(`开始批量合成 ${pendingItems.length} 条文本`)

      let successCount = 0
      let failCount = 0
      let captionSuccessCount = 0
      let captionFailCount = 0

      // 逐个合成
      for (const item of pendingItems) {
        item.synthesizing = true

        try {
          let result

          if (state.ttsProvider === 'openai') {
            // 使用OpenAI TTS
            result = await synthesizeSpeech(
              item.text,
              state.selectedModel,
              state.selectedVoice,
              useLanguageSelection.value ? state.selectedLanguage : null,
              supportsVoiceInstructions.value ? state.voiceInstructions : null
            )
          } else {
            // 使用Google TTS
            result = await synthesizeGoogleSpeech(
              item.text,
              googleTtsSettings.value.languageCode,
              googleTtsSettings.value.ssmlGender,
              googleTtsSettings.value.name,
              googleTtsSettings.value.speakingRate
            )
          }

          // 更新项目
          item.audioUrl = result.path
          item.duration = result.duration
          item.language = state.ttsProvider === 'openai'
            ? useLanguageSelection.value ? state.selectedLanguage : null
            : googleTtsSettings.value.languageCode
          item.synthesizing = false
          item.provider = state.ttsProvider
          successCount++

          // 保存到历史记录
          const historyItem = await addTtsHistory({
            name: item.name,
            text: item.text,
            originalName: item.originalName,
            originalText: item.originalText,
            audioPath: result.path,
            duration: result.duration,
            model: state.ttsProvider === 'openai' ? state.selectedModel : 'google-tts',
            voice: state.ttsProvider === 'openai' ? state.selectedVoice : googleTtsSettings.value.name,
            language: state.ttsProvider === 'openai'
              ? useLanguageSelection.value ? state.selectedLanguage : null
              : googleTtsSettings.value.languageCode,
            instructions: state.ttsProvider === 'openai'
              ? supportsVoiceInstructions.value ? state.voiceInstructions : null
              : JSON.stringify({
                ssmlGender: googleTtsSettings.value.ssmlGender,
                speakingRate: googleTtsSettings.value.speakingRate
              }),
            captionPath: item.captionPath || null,
            captionStatus: item.captionStatus || 'none',
            captionFormat: 'srt'
          })

          item.historyId = historyItem.id

          await updateTtsHistoryId(historyItem.id, item.historyId)

          // 更新文本列表，触发视图更新
          textItems.value = [...textItems.value]

          // 自动生成字幕
          if (state.autoGenerateCaption) {
            try {
              await action.generateCaptionAuto(item)
              captionSuccessCount++
              // 再次更新视图
              textItems.value = [...textItems.value]
            } catch (error) {
              captionFailCount++
              console.error(`字幕生成失败 (${item.name}):`, error)
            }
          }
        } catch (error) {
          console.error(`语音合成失败 (ID: ${item.id}):`, error)
          item.synthesizing = false
          failCount++
        }
      }

      let message = `批量合成完成，音频：成功${successCount}个，失败${failCount}个`
      if (captionSuccessCount > 0 || captionFailCount > 0) {
        message += `；字幕：成功${captionSuccessCount}个，失败${captionFailCount}个`
      }
      await MessagePlugin.success(message)

      // 如果在历史记录标签页，刷新历史记录
      if (state.activeTab === 'history') {
        action.loadHistory()
      }
    } catch (error) {
      console.error('批量合成失败:', error)
      await MessagePlugin.error('批量合成失败: ' + (error.message || '未知错误'))
    } finally {
      state.batchSynthesizing = false
    }
  },

  // 合成选中文本
  async synthesizeSelected() {
    if (!isReadyToSynthesize.value) {
      MessagePlugin.warning(
        state.ttsProvider === 'openai' ? '请先选择模型和语音' : '请先选择语言、性别和音色'
      )
      return
    }

    if (!hasPendingItems.value) {
      MessagePlugin.warning('没有待合成的文本')
      return
    }

    if (state.selectedItems.length <= 0) {
      MessagePlugin.warning('请选择文本')
      return
    }

    try {
      state.batchSynthesizing = true

      // 根据选中的ID获取对应的item对象
      const selectedItemObjects = textItems.value.filter((item) =>
        state.selectedItems.includes(item.id)
      )

      // 从选中的项目中筛选出待合成的项目
      const pendingItems = selectedItemObjects.filter(
        (item) => !item.audioUrl && !item.synthesizing
      )

      if (pendingItems.length === 0) {
        MessagePlugin.warning('选中的项目中没有待合成的文本')
        return
      }

      await MessagePlugin.info(`开始合成 ${pendingItems.length} 条文本`)

      let successCount = 0
      let failCount = 0
      let captionSuccessCount = 0
      let captionFailCount = 0

      // 逐个合成
      for (const item of pendingItems) {
        item.synthesizing = true

        try {
          let result

          if (state.ttsProvider === 'openai') {
            // 使用OpenAI TTS
            result = await synthesizeSpeech(
              item.text,
              state.selectedModel,
              state.selectedVoice,
              useLanguageSelection.value ? state.selectedLanguage : null,
              supportsVoiceInstructions.value ? state.voiceInstructions : null
            )
          } else {
            // 使用Google TTS
            result = await synthesizeGoogleSpeech(
              item.text,
              googleTtsSettings.value.languageCode,
              googleTtsSettings.value.ssmlGender,
              googleTtsSettings.value.name,
              googleTtsSettings.value.speakingRate
            )
          }

          // 更新项目
          item.audioUrl = result.path
          item.duration = result.duration
          item.language = state.ttsProvider === 'openai'
            ? useLanguageSelection.value ? state.selectedLanguage : null
            : googleTtsSettings.value.languageCode
          item.synthesizing = false
          item.synthesizing = false
          item.provider = state.ttsProvider
          successCount++

          // 保存到历史记录
          const historyItem = await addTtsHistory({
            name: item.name,
            text: item.text,
            originalName: item.originalName,
            originalText: item.originalText,
            audioPath: result.path,
            duration: result.duration,
            model: state.ttsProvider === 'openai' ? state.selectedModel : 'google-tts',
            voice: state.ttsProvider === 'openai' ? state.selectedVoice : googleTtsSettings.value.name,
            language: state.ttsProvider === 'openai'
              ? useLanguageSelection.value ? state.selectedLanguage : null
              : googleTtsSettings.value.languageCode,
            instructions: state.ttsProvider === 'openai'
              ? supportsVoiceInstructions.value ? state.voiceInstructions : null
              : JSON.stringify({
                ssmlGender: googleTtsSettings.value.ssmlGender,
                speakingRate: googleTtsSettings.value.speakingRate
              }),
            captionPath: item.captionPath || null,
            captionStatus: item.captionStatus || 'none',
            captionFormat: 'srt'
          })

          item.historyId = historyItem.id

          await updateTtsHistoryId(historyItem.id, item.historyId)

          // 更新文本列表，触发视图更新
          textItems.value = [...textItems.value]

          // 自动生成字幕
          if (state.autoGenerateCaption) {
            try {
              await action.generateCaptionAuto(item)
              captionSuccessCount++
              // 再次更新视图
              textItems.value = [...textItems.value]
            } catch (error) {
              captionFailCount++
              console.error(`字幕生成失败 (${item.name}):`, error)
            }
          }
        } catch (error) {
          console.error(`语音合成失败 (ID: ${item.id}):`, error)
          item.synthesizing = false
          failCount++
        }
      }

      let message = `合成完成，音频：成功${successCount}个，失败${failCount}个`
      if (captionSuccessCount > 0 || captionFailCount > 0) {
        message += `；字幕：成功${captionSuccessCount}个，失败${captionFailCount}个`
      }
      await MessagePlugin.success(message)

      // 如果在历史记录标签页，刷新历史记录
      if (state.activeTab === 'history') {
        await action.loadHistory()
      }
    } catch (error) {
      console.error('合成失败:', error)
      await MessagePlugin.error('合成失败: ' + (error.message || '未知错误'))
    } finally {
      state.batchSynthesizing = false
    }
  },

  // 将已合成的语音发送到视频制作
  sendToVideoCreation() {
    if (!hasCompletedItems.value) {
      MessagePlugin.warning('没有已合成的语音')
      return
    }

    // 获取所有已合成的项目
    const synthesizedItems = textItems.value.filter((item) => item.audioUrl)


    // 转换为批处理所需的格式
    const audioItems = synthesizedItems.map((item) => ({
      id: uuidv4(),
      type: 'audio',
      name: item.name,
      audioUrl: item.audioUrl,
      duration: item.duration
        ? `${Math.floor(item.duration / 60)}:${(item.duration % 60).toString().padStart(2, '0')}`
        : '未知时长',
      createdAt: new Date().toISOString(),
      provider: item.provider || 'openai', // 添加提供商信息
      caption_path: item.captionPath
    }))

    // 发送到父组件进行处理
    emit('sendToVideoCreation', audioItems)

    MessagePlugin.success(`已将 ${audioItems.length} 个合成语音发送到视频制作`)
  },

  // 将已合成的语音发送到视频制作
  async sendToVideoKpop() {
    if (!hasCompletedItems.value) {
      await MessagePlugin.warning('没有已合成的语音')
      return
    }

    // 获取所有已合成的项目
    const synthesizedItems = textItems.value.filter((item) => item.audioUrl)

    // 统计字幕情况
    const itemsWithoutCaption = synthesizedItems.filter(item => !item.captionPath || item.captionStatus !== 'completed')

    // 检查是否有项目缺少字幕
    if (itemsWithoutCaption.length > 0) {
      const confirmResult = await new Promise(resolve => {
        DialogPlugin({
          header: '部分项目没有字幕',
          body: `有 ${itemsWithoutCaption.length} 个项目没有生成字幕，是否继续？`,
          confirmBtn: '继续',
          cancelBtn: '取消',
          onConfirm: () => {
            resolve(true);
          },
          onCancel: () => {
            resolve(false);
          }
        })
      })

      if (!confirmResult) {
        return
      }
    }

    // 显示上传进度
    const loadingMessage = await MessagePlugin.loading({
      content: '正在上传文件到视频混剪服务...',
      duration: 0
    })

    try {
      let groupId = uuidv4()

      // 转换为批处理所需的格式，确保每个项目都有完整的信息
      const audioItems = synthesizedItems.map((item, index) => ({
        // 使用item本身的ID或生成新的，确保唯一性
        id: item.id || uuidv4(),
        type: 'audio',
        // 文案信息
        name: item.name || item.originalName || `音频_${index + 1}`,
        text: item.text || item.originalText || '',
        originalName: item.originalName || item.name,
        originalText: item.originalText || item.text,
        // 文件路径
        audioUrl: item.audioUrl,
        captionPath: item.captionPath || null,
        captionStatus: item.captionStatus || 'none',
        // 其他信息
        language: item.language || 'zh',
        duration: item.duration || 0,
        // 添加顺序标记
        order: index + 1
      }))

      // 调用上传函数
      let uploadResult = await sendVideoToKpop(audioItems, groupId)

      // 关闭加载提示
      loadingMessage.close()

      if (uploadResult.success) {
        // 显示详细的上传结果
        // 构建成功消息
        let successMessage = `✓ 成功上传 ${uploadResult.summary.success} 个文件`
        if (uploadResult.summary.withSubtitle > 0) {
          successMessage += `\n✓ 包含字幕: ${uploadResult.summary.withSubtitle} 个`
        }
        if (uploadResult.summary.success < uploadResult.summary.total) {
          successMessage += `\n⚠ 无字幕: ${uploadResult.summary.success - uploadResult.summary.withSubtitle} 个`
        }

        await MessagePlugin.success(successMessage)

        // 跳转到混剪页面
        await router.push({
          name: 'kpop',
          query: {
            ...route.query,
            src: `${assetPaths.value}:5173/merge?group_id=${groupId}`,
            // 传递额外的参数，让混剪页面知道有哪些文件
            hasCaption: uploadResult.summary.captionSuccess > 0
          }
        })
      } else {
        // 显示详细的错误信息
        let errorMessage = '上传失败'
        if (uploadResult.summary) {
          errorMessage += `\n音频失败: ${uploadResult.summary.audioFailed}个`
          if (uploadResult.summary.captionFailed > 0) {
            errorMessage += `\n字幕失败: ${uploadResult.summary.captionFailed}个`
          }
        }

        // 显示具体的错误项
        if (uploadResult.uploadResults) {
          const failedItems = uploadResult.uploadResults.filter(r => !r.audio?.success)
          if (failedItems.length > 0) {
            errorMessage += '\n失败项目:'
            failedItems.forEach(item => {
              const originalItem = audioItems.find(a => a.id === item.itemId)
              errorMessage += `\n- ${originalItem?.name || '未知'}: ${item.audio?.error || '未知错误'}`
            })
          }
        }

        await MessagePlugin.error({
          content: errorMessage,
          duration: 10000 // 显示10秒
        })

        kicked.value = false
        setTimeout(() => {
          kicked.value = true
        }, 10000)
      }
    } catch (error) {
      loadingMessage.close()
      console.error('发送到视频混剪失败:', error)

      await MessagePlugin.error({
        content: `发送失败: ${error.message || '未知错误'}`,
        duration: 5000
      })

      kicked.value = false
      setTimeout(() => {
        kicked.value = true
      }, 10000)
    }
  },

  // 预览音频
  previewAudio(item) {
    if (item.audioUrl) {
      props.listener.listen({
        name: item.name || '未命名',
        audioUrl: item.audioUrl
      })
    }
  },

  // 预览历史记录中的音频
  previewHistoryAudio(item) {
    if (item.audio_path) {
      props.listener.listen({
        name: item.name || '未命名',
        audioUrl: item.audio_path
      })
    } else {
      MessagePlugin.warning('音频文件不可用')
    }
  },

  // 使用历史记录中的音频
  useHistoryAudio(historyItem) {
    // 创建一个新的合成项
    const newItem = {
      id: historyItem.id,
      name: historyItem.name,
      text: historyItem.text,
      language: historyItem.language,
      originalText: historyItem.text_origin,
      originalName: historyItem.name_origin,
      audioUrl: historyItem.audio_path,
      duration: historyItem.duration,
      type: 'text', // 假设历史记录中的都是文本合成的音频
      instructions: historyItem.instructions, // 复制语音指令
      provider: historyItem.model === 'google-tts' ? 'google' : 'openai', // 设置提供商
      // 正确设置字幕相关字段
      captionPath: historyItem.caption_path,
      captionStatus: historyItem.caption_status || 'none',
      captionGenerating: false, // 确保不是生成中状态
      captionFormat: historyItem.caption_format || 'srt',
      historyId: historyItem.id, // 保持历史记录ID
      synthesizing: false // 确保不是合成中状态
    }

    // 添加到文本列表
    textItems.value.push(newItem)

    // 切换到当前任务标签页
    state.activeTab = 'current'

    MessagePlugin.success('已添加到当前任务')
  },

  // 使用选中的历史记录中的音频
  useHistoryAudios() {
    if (state.selectedHistoryItems.length === 0) {
      MessagePlugin.warning('请至少选择一条历史记录')
      return
    }

    // 获取选中的历史记录项
    const selectedItems = historyItems.value.filter((item) =>
      state.selectedHistoryItems.includes(item.id)
    )

    // 转换为批处理所需的格式
    const audioItems = selectedItems.map((item) => ({
      id: item.id,
      type: 'text',
      name: item.name,
      text: item.text,
      originalText: item.text_origin,
      originalName: item.name_origin,
      audioUrl: item.audio_path,
      duration: item.duration,
      language: item.language,
      // 正确设置字幕相关字段
      captionPath: item.caption_path,
      captionStatus: item.caption_status || 'none',
      captionGenerating: false,
      captionFormat: item.caption_format || 'srt',
      historyId: item.id,
      synthesizing: false
    }))

    // 添加到文本列表
    textItems.value.push(...audioItems)

    // 切换到当前任务标签页
    state.activeTab = 'current'

    MessagePlugin.success('已添加到当前任务')
  },

  // 删除单个项目
  deleteItem(id) {
    const item = textItems.value.find((item) => item.id === id)
    if (!item) return

    state.itemToDelete = id
    state.isHistoryItem = false
    state.deleteConfirmMessage = `确定要删除"${item.name || '未命名'}"吗？`
    state.deleteConfirmVisible = true
  },

  // 删除历史记录项目
  deleteHistoryItem(id) {
    const item = historyItems.value.find((item) => item.id === id)
    if (!item) return

    state.itemToDelete = id
    state.isHistoryItem = true
    state.deleteConfirmMessage = `确定要删除历史记录"${item.name || '未命名'}"吗？`
    state.deleteConfirmVisible = true
  },

  // 将历史记录中的所有音频发送到视频制作
  sendHistoryToVideoCreation() {
    if (!historyItems.value.length) {
      MessagePlugin.warning('没有可用的历史记录')
      return
    }

    // 转换为批处理所需的格式
    const audioItems = historyItems.value.map((item) => ({
      id: uuidv4(),
      type: 'audio',
      name: item.name,
      audioUrl: item.audio_path,
      duration: item.duration,
      language: item.language
        ? `${Math.floor(item.duration / 60)}:${(item.duration % 60).toString().padStart(2, '0')}`
        : '未知时长',
      createdAt: new Date(item.created_at).toISOString(),
      provider: item.model === 'google-tts' ? 'google' : 'openai'
    }))

    // 发送到父组件进行处理
    emit('sendToVideoCreation', audioItems)

    MessagePlugin.success(`已将 ${audioItems.length} 个历史语音发送到视频制作`)
  },

  // 确认删除（修改现有的 confirmDelete 方法）
  async confirmDelete() {
    if (state.isHistoryItem) {
      // 批量删除历史记录
      if (state.batchDeleteMode && state.selectedHistoryItems.length > 0) {
        try {
          // 显示加载状态
          state.historyLoading = true

          // 记录删除前的数量，用于计算成功数量
          const beforeCount = state.selectedHistoryItems.length

          // 逐个删除选中的历史记录
          let successCount = 0
          for (const id of state.selectedHistoryItems) {
            try {
              await deleteTtsHistory(id)
              successCount++
            } catch (error) {
              console.error(`删除历史记录 ${id} 失败:`, error)
            }
          }

          // 更新历史记录列表，移除已删除的项
          historyItems.value = historyItems.value.filter(
            (item) => !state.selectedHistoryItems.includes(item.id)
          )

          // 清空选择
          state.selectedHistoryItems = []

          MessagePlugin.success(`批量删除成功，已删除 ${successCount}/${beforeCount} 条历史记录`)
        } catch (error) {
          console.error('批量删除历史记录失败:', error)
          MessagePlugin.error('批量删除历史记录失败: ' + (error.message || '未知错误'))
        } finally {
          state.historyLoading = false
          state.batchDeleteMode = false
        }
      } else if (state.itemToDelete) {
        // 删除单个历史记录
        try {
          await deleteTtsHistory(state.itemToDelete)

          // 更新历史记录列表
          historyItems.value = historyItems.value.filter((item) => item.id !== state.itemToDelete)

          MessagePlugin.success('历史记录删除成功')
        } catch (error) {
          console.error('删除历史记录失败:', error)
          MessagePlugin.error('删除历史记录失败: ' + (error.message || '未知错误'))
        }
      } else {
        // 清空所有历史记录
        try {
          await deleteAllTtsHistory()

          // 清空历史记录列表
          historyItems.value = []

          MessagePlugin.success('所有历史记录已清空')
        } catch (error) {
          console.error('清空历史记录失败:', error)
          MessagePlugin.error('清空历史记录失败: ' + (error.message || '未知错误'))
        }
      }
    } else if (state.itemToDelete) {
      // 单个删除当前项目（原有逻辑不变）
      textItems.value = textItems.value.filter((item) => item.id !== state.itemToDelete)

      // 如果在选择列表中，也要移除
      if (state.selectedItems.includes(state.itemToDelete)) {
        state.selectedItems = state.selectedItems.filter((id) => id !== state.itemToDelete)
      }

      MessagePlugin.success('删除成功')
    } else if (state.selectedItems.length > 0) {
      // 批量删除（原有逻辑不变）
      textItems.value = textItems.value.filter((item) => !state.selectedItems.includes(item.id))
      state.selectedItems = []
      MessagePlugin.success('批量删除成功')
    } else {
      // 清空所有（原有逻辑不变）
      textItems.value = []
      state.selectedItems = []
      MessagePlugin.success('清空成功')
    }

    // 重置状态
    state.itemToDelete = null
    state.isHistoryItem = false
    state.batchDeleteMode = false
    state.deleteConfirmVisible = false
  },

  // 清空所有项目
  clearAll() {
    state.deleteConfirmMessage = '确定要清空所有文本吗？'
    state.itemToDelete = null
    state.isHistoryItem = false
    state.deleteConfirmVisible = true
  },

  // 清空所有历史记录
  clearAllHistory() {
    if (!historyItems.value.length) {
      MessagePlugin.warning('没有历史记录可清空')
      return
    }

    state.deleteConfirmMessage = '确定要清空所有历史记录吗？此操作不可恢复。'
    state.isHistoryItem = true
    state.itemToDelete = null // null 表示清空所有
    state.deleteConfirmVisible = true
  },

  // 切换选择项目
  toggleSelectItem(id) {
    if (state.selectedItems.includes(id)) {
      state.selectedItems = state.selectedItems.filter((itemId) => itemId !== id)
    } else {
      state.selectedItems.push(id)
    }
  },

  // 加载历史记录
  async loadHistory() {
    try {
      state.historyLoading = true
      historyItems.value = await getAllTtsHistory()

      // 加载后切换到第一页
      state.historyPagination.current = 1
      state.selectedHistoryItems = []
    } catch (error) {
      console.error('加载历史记录失败:', error)
      MessagePlugin.error('加载历史记录失败: ' + (error.message || '未知错误'))
    } finally {
      state.historyLoading = false
    }
  },

  // 刷新历史记录
  refreshHistory() {
    state.historySearchTerm = ''
    action.loadHistory()
  },

  // 搜索历史记录
  async searchHistory() {
    if (!state.historySearchTerm.trim()) {
      return action.loadHistory()
    }

    try {
      state.historyLoading = true
      const records = await searchTtsHistory(state.historySearchTerm)
      historyItems.value = records
      // 搜索后切换到第一页
      state.historyPagination.current = 1
      state.selectedHistoryItems = []
      MessagePlugin.info(`找到 ${records.length} 条相关记录`)
    } catch (error) {
      console.error('搜索历史记录失败:', error)
      MessagePlugin.error('搜索历史记录失败: ' + (error.message || '未知错误'))
    } finally {
      state.historyLoading = false
    }
  }
}

onMounted(async () => {
  await getBaseUrl().then((result) => {
    assetPaths.value = result
  })

  // 加载可用的语音和模型列表
  await loadData()

  // 加在谷歌可用的语音
  await loadGoogleVoices()

  // 加载保存的配置
  const savedConfig = localStorage.getItem('tts-batch-config')
  if (savedConfig) {
    try {
      const config = JSON.parse(savedConfig)
      // 恢复自动生成字幕的配置
      if (config.autoGenerateCaption !== undefined) {
        state.autoGenerateCaption = config.autoGenerateCaption
      }
      // 恢复其他配置（如果有的话）
      if (config.selectedModel) {
        state.selectedModel = config.selectedModel
      }
      if (config.selectedVoice) {
        state.selectedVoice = config.selectedVoice
      }
      if (config.ttsProvider) {
        state.ttsProvider = config.ttsProvider
      }
    } catch (error) {
      console.error('加载配置失败:', error)
    }
  }
})
</script>

<style lang="less" scoped>

.auto-caption-settings {
  padding: 12px 16px;
  margin: 12px 0;
  background-color: var(--td-bg-color-container-hover);
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 12px;

  .setting-tip {
    font-size: 12px;
    color: var(--td-text-color-placeholder);
  }
}

.history-caption-status {
  margin-top: 4px;
}

.caption-dropdown {
  .t-dropdown-menu {
    min-width: 120px;
  }
}

// 调整操作按钮布局以容纳更多按钮
.text-actions,
.history-actions {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: wrap;

  .t-button {
    min-width: auto;
    padding: 0 8px;

    &:has(.t-icon):not(:has(.t-button__text)) {
      padding: 0 8px;
    }
  }
}

:deep(.t-dialog__ctx .t-dialog__position.t-dialog--top) {
  padding-top: 1em;
}

/* 批量删除按钮样式 */
.batch-controls {
  .t-button.t-button--theme-danger {
    background-color: rgba(227, 77, 89, 0.05); // 淡化危险按钮背景色
    color: #e34d59;
    border-color: #e34d59;

    &:hover {
      background-color: rgba(227, 77, 89, 0.1); // 淡化悬停效果
    }
  }
}

.batch-actions {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding: 12px 16px;
  background-color: var(--td-bg-color-container-hover);
  border-radius: 6px;
}

.batch-info {
  margin-left: 16px;
  font-weight: 500;
  color: var(--td-brand-color);
}

.batch-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-left: auto;
}

/* 修改历史记录底部按钮布局 */
.history-actions {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e0; // 深色边框改为浅灰色
}

/* 历史记录多选相关样式 */
.history-batch-actions {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
  padding: 12px;
  background: #f5f5f5; // 深色背景改为浅灰色
  border-radius: 4px;
  border: 1px solid #e0e0e0; // 深色边框改为浅灰色

  .batch-info {
    color: rgba(0, 0, 0, 0.8); // 半透明白色改为半透明黑色
    font-size: 14px;
  }

  .batch-controls {
    display: flex;
    gap: 8px;
    margin-left: auto;
  }
}

.history-item {
  /* 添加选中样式 */
  &.selected {
    border-color: var(--td-brand-color);
    background-color: rgba(0, 82, 217, 0.05); // 淡化选中背景色
  }

  /* 添加选择框样式 */
  .item-select {
    margin-right: 12px;

    :deep(.t-checkbox) {
      --td-checkbox-color: rgba(0, 0, 0, 0.8); // 半透明白色改为半透明黑色
    }
  }
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: center;
  padding: 12px;
  background: #f5f5f5; // 深色背景改为浅灰色
  border-radius: 4px;
  border: 1px solid #e0e0e0; // 添加边框增强视觉定义

  :deep(.t-pagination) {
    --td-bg-color-component: #ffffff; // 深色背景改为白色
    --td-text-color-primary: #333333; // 黑色文本改为深灰色
    --td-bg-color-container: #ffffff; // 容器背景改为白色
    --td-text-color-secondary: rgba(0, 0, 0, 0.6); // 半透明白色改为半透明黑色
    --td-brand-color: #0052d9; // 保持品牌色不变

    .t-button {
      background-color: #ffffff; // 深色按钮背景改为白色
      border-color: #e0e0e0; // 深色边框改为浅灰色

      &:hover {
        background-color: #f5f5f5; // 深色悬停背景改为浅灰色
      }

      &.t-is-active {
        background-color: var(--td-brand-color);
        color: #fff; // 保持激活状态的白色文本
      }
    }

    .t-select {
      background-color: #ffffff; // 深色选择器背景改为白色
      border-color: #e0e0e0; // 深色边框改为浅灰色
      color: #333333; // 白色文本改为深灰色
    }
  }
}

.tts-batch {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #ffffff; // 深色背景改为白色
  color: #333333; // 白色文本改为深灰色

  &-header {
    padding: 16px;
    border-bottom: 1px solid #e0e0e0; // 深色边框改为浅灰色

    .title {
      font-weight: 500;
      font-size: 16px;
      color: #333333; // 白色文本改为深灰色
    }

    .status {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.6); // 半透明白色改为半透明黑色
      float: right;
    }
  }

  &-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: auto;

    .main-tabs {
      flex: 1;
      display: flex;
      flex-direction: column;
      height: 100%;
      padding: 1em;

      :deep(.t-tabs__header) {
        border-bottom-color: #e0e0e0; // 深色边框改为浅灰色
        background-color: #ffffff; // 深色背景改为白色
      }

      :deep(.t-tabs__nav) {
        border-bottom-color: #e0e0e0; // 深色边框改为浅灰色
        background-color: #ffffff; // 深色背景改为白色
      }

      :deep(.t-tabs__nav-item) {
        color: rgba(0, 0, 0, 0.6); // 半透明白色改为半透明黑色
        background-color: #ffffff; // 深色背景改为白色

        &.t-is-active {
          color: #0052d9; // 白色改为品牌蓝色
        }
      }

      :deep(.t-tabs__content) {
        flex: 1;
        overflow: auto;
        background-color: #ffffff; // 深色背景改为白色
      }

      :deep(.t-tabs__panel) {
        height: 100%;
        padding: 16px;
        background-color: #ffffff; // 深色背景改为白色
      }
    }
  }

  .tts-settings {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
    padding-bottom: 16px;
    padding-left: 16px;
    border-bottom: 1px solid #e0e0e0; // 深色边框改为浅灰色
    background-color: #f9f9f9; // 添加背景色，区分功能区

    .setting-item {
      display: flex;
      align-items: center;
      gap: 8px;

      .setting-label {
        white-space: nowrap;
        font-size: 14px;
        color: #333333; // 白色文本改为深灰色
      }

      .setting-select {
        width: 180px;
        --td-bg-color-specialcomponent: #ffffff; // 深色背景改为白色
        --td-text-color-primary: #333333; // 白色文本改为深灰色
        --td-text-color-placeholder: rgba(0, 0, 0, 0.4); // 半透明白色改为半透明黑色

        :deep(.t-select__input) {
          background-color: #ffffff; // 深色背景改为白色
          border-color: #e0e0e0; // 深色边框改为浅灰色
          color: #333333; // 白色文本改为深灰色

          &:hover,
          &:focus {
            border-color: #0052d9; // 添加悬停和聚焦状态
          }
        }

        :deep(.t-popup) {
          background-color: #ffffff; // 深色背景改为白色
          border: 1px solid #e0e0e0; // 深色边框改为浅灰色
        }

        :deep(.t-select-option) {
          color: #333333; // 白色文本改为深灰色
          background-color: #ffffff; // 深色背景改为白色

          &:hover,
          &.t-is-selected {
            background-color: #f5f5f5; // 深色悬停背景改为浅灰色
          }
        }
      }
    }
  }

  .text-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .left-actions,
    .right-actions {
      display: flex;
      align-items: center;
      gap: 12px;
    }
  }

  .text-list,
  .history-list {
    flex: 1;
    overflow: auto;

    .empty-state,
    .history-loading {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 260px;
      color: rgba(0, 0, 0, 0.6); // 半透明白色改为半透明黑色
    }

    .text-items,
    .history-items {
      display: flex;
      flex-direction: column;
      gap: 12px;

      &:last-child {
        margin-bottom: 12px;
      }
    }

    .text-item,
    .history-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px;
      background: #fafafa; // 深色背景改为浅灰白色
      border-radius: 4px;
      border: 1px solid #e0e0e0; // 深色边框改为浅灰色
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03); // 添加轻微阴影增强立体感

      &:hover {
        background-color: #f5f5f5; // 添加悬停效果
      }

      &.synthesized {
        border-color: #4caf50; // 保持合成状态的绿色边框
      }

      &.selected {
        border-color: var(--td-brand-color);
        background-color: rgba(0, 82, 217, 0.05); // 淡化选中背景色
      }

      .item-select {
        margin-right: 8px;
      }

      .text-content,
      .history-content {
        flex: 1;
        min-width: 0;

        .text-title,
        .history-title {
          font-weight: 500;
          font-size: 14px;
          color: #333333; // 白色文本改为深灰色
          margin-bottom: 4px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .text-preview,
        .history-text {
          font-size: 12px;
          color: rgba(0, 0, 0, 0.6); // 半透明白色改为半透明黑色
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .history-info {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 4px;

          .history-time {
            font-size: 12px;
            color: rgba(0, 0, 0, 0.5); // 半透明白色改为半透明黑色
          }
        }

        // 添加历史记录中的指令标记样式
        .history-instructions {
          margin-top: 4px;
        }
      }

      .text-status {
        margin-right: 8px;

        :deep(.t-tag) {
          white-space: nowrap;
        }
      }

      .text-actions,
      .history-actions {
        display: flex;
        align-items: center;
        gap: 8px;

        .t-button {
          min-width: 48px;
          height: 32px;
          border-radius: 4px;
          font-size: 12px;
        }
      }
    }
  }

  .history-search {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;

    .t-input {
      flex: 1;
      --td-bg-color-specialcomponent: #ffffff; // 深色背景改为白色
      --td-text-color-primary: #333333; // 白色文本改为深灰色
      --td-text-color-placeholder: rgba(0, 0, 0, 0.4); // 半透明白色改为半透明黑色

      :deep(.t-input__inner) {
        background-color: #ffffff; // 深色背景改为白色
        border-color: #e0e0e0; // 深色边框改为浅灰色
        color: #333333; // 白色文本改为深灰色

        &:hover,
        &:focus {
          border-color: #0052d9; // 添加悬停和聚焦状态
        }
      }
    }
  }

  .tts-actions {
    display: flex;
    justify-content: space-between;
    gap: 12px;
    padding-top: 16px;
    border-top: 1px solid #e0e0e0; // 深色边框改为浅灰色

    .t-button {
      flex: 1;
    }
  }
}

.t-dialog {
  :deep(.t-dialog__body) {
    background-color: #ffffff; // 深色背景改为白色
    color: #333333; // 白色文本改为深灰色
  }

  :deep(.t-dialog__header) {
    background-color: #ffffff; // 深色背景改为白色
    color: #333333; // 白色文本改为深灰色
    border-bottom: 1px solid #e0e0e0; // 添加边框分隔
  }

  :deep(.t-dialog__footer) {
    background-color: #ffffff; // 深色背景改为白色
    border-top: 1px solid #e0e0e0; // 添加边框分隔
  }
}

/* 下拉菜单样式 */
:deep(.t-select__dropdown) {
  background-color: #ffffff; // 深色背景改为白色
  border-color: #e0e0e0; // 深色边框改为浅灰色
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); // 添加阴影增强立体感

  .t-select-option {
    color: #333333; // 白色文本改为深灰色

    &:hover,
    &.t-is-selected {
      background-color: #f5f5f5; // 深色悬停背景改为浅灰色
    }
  }
}

/* 按钮悬停样式 */
:deep(.t-button) {
  &.t-button--theme-primary:not(:disabled):hover {
    background-color: rgba(0, 82, 217, 0.9); // 保持原有效果
  }

  &.t-button--theme-success:not(:disabled):hover {
    background-color: rgba(0, 168, 112, 0.9); // 保持原有效果
  }

  &.t-button--theme-danger:not(:disabled):hover {
    background-color: rgba(227, 77, 89, 0.9); // 保持原有效果
  }
}

/* 标签样式 */
:deep(.t-tag) {
  &.t-tag--theme-success {
    background-color: rgba(0, 168, 112, 0.1); // 保持原有效果
    color: #4caf50;
  }

  &.t-tag--theme-warning {
    background-color: rgba(255, 170, 0, 0.1); // 保持原有效果
    color: #ff9800;
  }

  &.t-tag--theme-default {
    background-color: rgba(0, 0, 0, 0.05); // 半透明白色改为半透明黑色
    color: rgba(0, 0, 0, 0.6); // 半透明白色改为半透明黑色
  }

  &.t-tag--theme-primary {
    background-color: rgba(0, 82, 217, 0.1); // 保持原有效果
    color: #0052d9;
  }
}

/* 滚动条样式 */
.text-list,
.history-list {
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #d0d0d0; // 深色滚动条改为浅灰色
    border-radius: 3px;
  }

  scrollbar-width: thin;
  scrollbar-color: #d0d0d0 transparent; // 深色滚动条改为浅灰色
}

.history-content {
  display: flex;
  flex-direction: column;
  height: 100%;

  .history-list {
    flex: 1;
    overflow: auto;
    margin-bottom: 16px;
  }

  .history-actions {
    display: flex;
    justify-content: space-between;
    gap: 12px;
    padding-top: 16px;
    border-top: 1px solid #e0e0e0; // 深色边框改为浅灰色

    .t-button {
      min-width: 120px;
    }
  }
}
</style>
